from google.appengine.ext import db

class DBAnswer(db.Model):
    date = db.DateTimeProperty(auto_now_add=True)
    value = db.IntegerProperty()
    questionId = db.IntegerProperty()
    userId = db.IntegerProperty()

class Answer():
    def __init__(self, qId, uId, value):
        self.questionId = qId
        self.date = None
        self.userId = uId
        self.value = value
        self.id = -1

    def save(self):
        if self.id != -1:
            return False
        dbAnswer = DBAnswer();
        dbAnswer.questionId = int(self.questionId)
        dbAnswer.userId = int(self.userId)
        dbAnswer.value = int(self.value)
        dbAnswer.put()
        self.date = dbAnswer.date
        self.id = dbAnswer.key().id()
            

    def loadFromId(self, id):
        key = db.Key.from_path('DBAnswer', long(id))
        dbAnswer = db.get(key)
        if dbAnser == None:
            return None
        self.questionId = dbAnswer.questionId
        self.userId = dbAnswer.userId
        self.value = dbAnswer.value
        self.date = dbAnswer.date
        self.id = id
        return True

def loadAnswersFromQId(qId):
    dbAnswerQ = db.GqlQuery("SELECT * FROM DBAnswer WHERE questionId=:1 ORDER BY date", int(qId))
    answers = []
    for dbAnswer in dbAnswerQ:
        answer = Answer(dbAnswer.questionId, dbAnswer.userId, dbAnswer.value)
        answer.id = dbAnswer.key().id()
        answer.date = dbAnswer.date
        answers.append(answer)
    return answers

def loadAnswersFromUserId(uId):
    dbAnswerQ = db.GqlQuery("SELECT * FROM DBAnswer WHERE userId=:1 ORDER BY date", int(uId))
    answers = []
    for dbAnswer in dbAnswerQ:
        answer = Answer(dbAnswer.questionId, dbAnswer.userId, dbAnswer.value)
        answer.id = dbAnswer.key().id()
        answer.date = dbAnswer.date
        answers.append(answer)
    return answers
